<template>

  <div style="padding: 20px; background: #fff; min-height: calc(100vh - 50px)">
    <div style="display: flex; margin-top: 50px; min-height: 80px">
      <div class="qus">问</div>
      <div style="font-size: 16px; line-height: 30px">
        <div v-html="content"></div>
        <!-- <p>{{ community.content }}</p> -->
      </div>
    </div>
    <div
      style="
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        width: 100%;
        color: #787878; 
        font-weight: 200;
      "
    >
      <div style="display: flex" @click="toUser(community.buser?.id)" class="user">
        <div>
          <el-avatar :size="30" :src="community.buser?.avatar" @error="true">
            <span style="font-size: 12px">{{ community.buser?.nickname }}</span>
          </el-avatar>
        </div>
        <div style="line-height: 30px; margin-left: 10px">
          提问于&nbsp;{{ titleUtil.formatDate(community?.createTime) }}&nbsp;
          <el-tooltip :content="titleUtil.formatDate(community?.createTime)">
            <i class="iconfont icon-icon-test58"></i>
          </el-tooltip>
        </div>
      </div>
      <div style="display: flex">
        <div style="display: flex; width: 100px; text-align: center">
          <i class="iconfont icon-biaoqian"></i>
          回答
          <div style="margin-left: 5px">{{ titleUtil.numberTo(community?.reviewCount) }}</div>
        </div>
        <div
          style="display: flex; width: 100px; text-align: center"
          class="like"
          @click="likes(community?.id)"
        >
          <i class="iconfont icon-icon-test35"></i>
          点赞
          <div style="margin-left: 5px">{{ titleUtil.numberTo(community?.likeCount) }}</div>
        </div>
        <div style="display: flex; width: 100px; text-align: center">
          <i class="iconfont icon-icon-test"></i>
          查看
          <div style="margin-left: 5px">{{ titleUtil.numberTo(community?.look) }}</div>
        </div>
      </div>
    </div>
    <div class="line"></div>
    <div id="mark">
      <el-button
        @click="showText"
        :icon="Edit"
        style="width: 240px; background: #1100ff; height: 40px; color: #fff; margin-bottom: 20px"
        >写回答</el-button
      >
      <div v-if="isText">
        <vue3-tinymce v-model="review.content" :setting="state.setting" :init="init" />
        <div style="width: 100%; text-align: right; margin-top: 5px">
          <el-button type="primary" @click="submitReview">提交</el-button>
          <el-button @click="reset">取消</el-button>
        </div>
      </div>
    </div>
    <div class="line"></div>
    <div style="">
      <div
        style="
          display: flex;
          justify-content: space-between;
          width: 100%;
          border-bottom: #e3e3e3 1px solid;
          padding-bottom: 8px;
        "
      >
        <div style="font-size: 18px; display: flex">
          回答
          <div style="margin-left: 10px">{{ community?.reviewCount }}</div>
        </div>
        <div style="display: flex">
          <div><el-button @click="latest">推荐</el-button></div>
          <div><el-button @click="recommend">最新</el-button></div>
        </div>
      </div>
      <div style="padding: 10px">
        <div v-if="community?.reviewCount === 0 ? true : false" style="display: flex">
          <div style="width: 60px; text-align: center; margin-top: 15px">
            <el-avatar :icon="UserFilled" :size="30" />
          </div>
          <div
            style="
              flex: 1;
              background: rgba(142, 202, 255, 0.09);
              text-align: center;
              line-height: 60px;
              color: #787878;
            "
          >
            <span
              >成为首答用户，去<a @click="toMark" style="color: #1100ff" class="item"
                >写回答</a
              ></span
            >
          </div>
        </div>
        <div v-else>
          <div style="margin-bottom: 20px" v-for="review of community.reviewList" :key="review.id">
            <div style="display: flex; justify-content: space-between">
              <div style="display: flex">
                <div style="width: 30px">
                  <el-avatar :size="30" :src="review.user?.avatar" @error="true">
                    <span style="font-size: 12px">{{ review.user?.nickname }}</span>
                  </el-avatar>
                </div>
                <div style="margin-left: 10px; line-height: 30px; font-size: 14px; color: #1100ff">
                  <span>{{ review.user?.nickname }}</span>
                </div>
              </div>
              <div style="color: #787878; font-size: 12px">
                发布于&nbsp;{{ titleUtil.formatDate(review.createTime) }}
              </div>
            </div>
            <div style="padding: 10px 0; margin: 10px 0 10px 40px">
              <div v-html="reviews(review.communityReviewContent)"></div>
            </div>
            <div style="display: flex; font-size: 12px; color: #787878; margin-left: 40px">
              <div class="like" @click="like(review.id)">
                <i class="iconfont icon-aixin1"></i>&nbsp;{{ review.likeCount }}
              </div>
              <div style="margin-left: 20px" class="review" @click="showChild(review?.id)">
                <i class="iconfont icon-icon-test2"></i>&nbsp;{{
                  review.childCommunity === null ? 0 : review.childCommunity?.length
                }}
              </div>
            </div>
            <div
              v-if="cReview.indexOf(review.id) !== -1 ? true : false"
              style="margin-left: 40px; padding: 10px 0"
            >
              <div class="inputDeep" style="width: 100%">
                <el-input
                  v-model="childReview.content"
                  maxlength="30"
                  style="width: 100%"
                  placeholder="写下你的评论"
                  show-word-limit
                  type="textarea"
                />
                <div style="width: 100%; text-align: right">
                  <el-button
                    size="small"
                    style="width: 160px; height: 30px"
                    @click="submitCReview(review.id)"
                    >发表</el-button
                  >
                </div>
              </div>
              <div class="childre">
                <ReviewChildVue
                  :dataList="review.childCommunity"
                  @like="handlerLike"
                  @review="handlerReview"
                ></ReviewChildVue>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import request from '@/util/request'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import titleUtil from '@/util/titleUtil'
import Vue3Tinymce from '@jsdawn/vue3-tinymce'
import { UserFilled, Edit } from '@element-plus/icons-vue'
import ReviewChildVue from '@/components/client/community/ReviewChild.vue'

const route = useRoute()
const router = useRouter()
const community = ref({})
const isText = ref(false)
const cReview = ref([])
const review = reactive({
  communityId: null,
  content: '',
  puserId: null
})
const childReview = ref({
  communityId: null,
  content: '',
  puserId: null
})

const content = computed(() => {
  if (community.value && community.value.content) {
    // 如果已定义，则替换换行符为 <br>
    return community.value.content.replace(/\n/g, '<br>')
  } else {
    return community.value.content
  }
})
const reviews = (text) => {
  return text
}

const state = reactive({
  // editor 配置项
  setting: {
    height: 400, // editor 高度
    language: 'zh-Hans',
    language_url: 'https://unpkg.com/@jsdawn/vue3-tinymce@2.0.2/dist/tinymce/langs/zh-Hans.js'
  }
})

const communityId = route.params.id

const showText = () => {
  isText.value = !isText.value
}
const submitReview = () => {
  console.log('数据', review)
  review.communityId = communityId
  request
    .post('/user/review/insert', review)
    .then((res) => {
      console.log('获取成功：', res)
      ElNotification.success('发布成功，等待审核')
      getCommunityDetail()
      review.communityId = null
      review.content = ''
      review.puserId = null
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}
const handlerReview = (id, content) => {
  childReview.value.content = content
  submitCReview(id)
}

const submitCReview = (id) => {
  childReview.value.communityId = communityId
  childReview.value.puserId = id
  request
    .post('/user/review/insert', childReview.value)
    .then((res) => {
      console.log('获取成功：', res)
      ElNotification.success('发布成功，等待审核')
      getCommunityDetail()
      childReview.value.communityId = null
      childReview.value.content = ''
      childReview.value.puserId = null
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const showChild = (id) => {
  if (cReview.value.indexOf(id) === -1) {
    cReview.value.push(id)
  } else {
    cReview.value.pop(cReview.value.indexOf(id), 1)
  }
}

const getCommunityDetail = () => {
  request
    .get(`/user/community/detail?id=${communityId}`)
    .then((res) => {
      console.log('获取成功：', res)
      community.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const toUser = (userId) => {
  router.push({ name: 'UserPage', params: { userId: userId } })
}

const toMark = () => {
  const tiny = document.getElementById('mark')
  tiny.scrollIntoView({ behavior: 'smooth' }) //平滑滚动到元素位置
  isText.value = true
}

const recommend = () => {
  console.log(community.value.reviewList)
  const arr = community.value.reviewList.sort((a, b) => {
    return new Date(a.createTime) - new Date(b.createTime)
  })
  console.log(arr)
}
const latest = () => {
  console.log(community.value.reviewList)
  const arr = community.value.reviewList.sort((a, b) => {
    return a.likeCount - b.likeCount
  })
  console.log(arr)
}
// 点赞事件
const handlerLike = (id) => {
  like(id)
}
// 给评论点赞
const like = (id) => {
  console.log('给', id, '点赞了')
  request
    .get(`/user/review/like?id=${id}`)
    .then((res) => {
      console.log('获取成功：', res)
      ElNotification.success('点赞成功')
      getCommunityDetail()
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}
// 给问答点赞
const likes = (id) => {
  request
    .get(`/user/community/like?id=${id}`)
    .then((res) => {
      console.log('获取成功：', res)
      ElNotification.success('点赞成功')
      getCommunityDetail()
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}
onMounted(() => {
  getCommunityDetail()
})
</script>

<style scoped>
.qus {
  width: 30px;
  height: 30px;
  margin-right: 15px;
  line-height: 30px;
  background: #1100ff;
  color: #fff;
  text-align: center;
  border-radius: 2px;
}
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(191, 255, 0));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
.line {
  margin: 20px 0 20px 0;
  border: 1px #e3e3e3 solid;
}
.user:hover {
  cursor: pointer;
  background: #eee;
}
.item:hover {
  cursor: pointer;
}
.like:hover {
  color: #1100ff;
  cursor: pointer;
}
.review:hover {
  color: #1100ff;
  cursor: pointer;
}
.inputDeep >>> .el-textarea__inner {
  border: 0;
  resize: none; /* 这个是去掉 textarea 下面拉伸的那个标志，如下图 */
}
.childre {
  margin-top: 20px;
  background: #e3e3e349;
  border-radius: 4px;
}
</style>
